package com.sdruixinggroup.mondayb2b.ui.fragments;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.AddressDetail;
import com.sdruixinggroup.mondayb2b.models.ModelBeen;
import com.sdruixinggroup.mondayb2b.models.Province;
import com.sdruixinggroup.mondayb2b.ui.Activities.CityListActivity;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by 00029935 on 2017/12/4.
 */

public class AddNewAddressFragment extends BaseFragment {
    @BindView(R.id.ib_back)
    ImageView ibBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_choice_address)
    LinearLayout llChoiceAddress;
    @BindView(R.id.et_detail_address)
    EditText etDetailAddress;
    @BindView(R.id.cb_default)
    CheckBox cbDefault;
    @BindView(R.id.tv_add_new_address)
    TextView tvAddNewAddress;
    private Province.RegionsBean myProvince;
    private Province.RegionsBean myCity;
    private Province.RegionsBean myArea;
    private int is_default = 0;

    private int id = -1;



    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        id = getActivity().getIntent().getIntExtra("ID",-1);
    }

    @Override
    protected int getInflateLayout() {
        return R.layout.add_new_address_fragment;
    }

    @Override
    protected void setUpView(View view) {
        if(id != -1) {
            tvTitle.setText("编辑地址");
        }else {
            tvTitle.setText("添加新地址");
        }
        ibBack.setImageResource(R.mipmap.share_back);

        cbDefault.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                is_default = isChecked?1:0;
            }
        });

        if(id != -1){
            queryDetail(id);
        }

        if(id==-1){
            cbDefault.setChecked(true);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @OnClick({R.id.ib_back, R.id.ll_choice_address, R.id.tv_add_new_address})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_back:
                getActivity().finish();
                break;
            case R.id.ll_choice_address:
                Intent integer = new Intent(getContext(), CityListActivity.class);
                startActivityForResult(integer,3);

                break;
            case R.id.tv_add_new_address:
                String consignee = etName.getText().toString().trim();
                if(TextUtils.isEmpty(consignee)){
                    showMsgToast("请输入收货人姓名");
                    return;
                }

                String phone = etPhone.getText().toString().trim();
                if(TextUtils.isEmpty(phone)){
                    showMsgToast("请输入手机号");
                    return;
                }else {
                    if(phone.length() != 11){
                        showMsgToast("手机号有误，请重新输入！");
                        return;
                    }
                }

                String detail = etDetailAddress.getText().toString().trim();
                if(TextUtils.isEmpty(detail)){
                    showMsgToast("请输入详细地址");
                    return;
                }
                if(null == myProvince){
                    showMsgToast("请选择地区");
                    return;
                }
                queryData(consignee,phone,myProvince.getId(),myCity.getId(),myArea.getId(),detail,is_default);
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode != Activity.RESULT_OK){
            return;
        }
        switch (requestCode){
            case 3:

                myProvince=(Province.RegionsBean)data.getSerializableExtra("Province");
                myCity=(Province.RegionsBean)data.getSerializableExtra("City");
                myArea=(Province.RegionsBean)data.getSerializableExtra("Area");
                String address = myProvince.getName()+"-"+myCity.getName()+"-"+myArea.getName();
                tvAddress.setText(address);
                break;
        }
    }

    private void queryData(String consignee,String phone,int province_id,int city_id,int county_id,String street,int is_default){
        String url = API.MEMBER_ADDRESS+
                "consignee="+consignee+
                "&phone="+phone+
                "&province_id="+province_id+
                "&city_id="+city_id+
                "&county_id="+county_id+
                "&street="+street+
                "&is_default="+is_default+
                "&id="+id+
                "&access_token="+ UserInfoUtil.getInfoToken(getContext());


        HashMap<String,String> header = new HashMap<>();
        header.put("Accept","*/*");

        TypeToken<ModelBeen> typeToken = new TypeToken<ModelBeen>(){};
        OkHttpUtils.post().url(url).headers(header).build().execute(new ObjectCallBack<ModelBeen>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(ModelBeen response, int id) {
                    if(response.err_code == 0){
                        showMsgToast("保存成功！");
                        getActivity().finish();
                    }else {
                        showMsgToast(response.err_msg);
                    }
            }
        });
    }

    private void queryDetail(int id){
        String url = API.MEMBER_ADDRESSES_DEFAULT+id+"?"+"access_token="+UserInfoUtil.getInfoToken(getContext());
        HashMap<String,String> header = new HashMap<>();
        header.put("Accept","*/*");
        TypeToken<AddressDetail> typeToken = new TypeToken<AddressDetail>(){};
        OkHttpUtils.get().url(url).headers(header).build().execute(new ObjectCallBack<AddressDetail>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(AddressDetail response, int id) {
                        if(null != response){
                            if(response.getErr_code() == 0){
                                AddressDetail.AddressBean addressBean= response.getAddress();
                                etName.setText(addressBean.getConsignee());
                                etPhone.setText(addressBean.getPhone());
                                myProvince = new Province.RegionsBean();
                                myProvince.setId(addressBean.getProvince_id());
                                myProvince.setName(addressBean.getProvince_name());
                                myCity = new  Province.RegionsBean();
                                myCity.setName(addressBean.getCity_name());
                                myCity.setId(addressBean.getCity_id());
                                myArea = new Province.RegionsBean();
                                myArea.setName(addressBean.getCounty_name());
                                myArea.setId(addressBean.getCounty_id());
                                String address = myProvince.getName()+"-"+myCity.getName()+"-"+myArea.getName();
                                tvAddress.setText(address);

                                etDetailAddress.setText(addressBean.getStreet());

                                int defaul = addressBean.getIs_default();
                                cbDefault.setChecked(defaul == 1?true:false);
                            }else {
                               showMsgToast(response.getErr_msg());
                            }
                        }

            }
        });
    }
}
